<script setup lang="ts">
import PrizeCard from "./components/PrizeCard.vue";
import { Button, message } from "ant-design-vue";
import { computed, nextTick, onMounted, ref, watch, onUnmounted } from "vue";
import { Member } from "./member";
import { displayPrize, IRound } from "./interface";
import TurnMusic from "./assets/抽奖转动音乐.mp3";
import ResultMusic from "./assets/抽奖结果音乐.mp3";
const tagCanvas = (window as any).TagCanvas;
import axios from "axios";
import { useKeyMap } from "./keymap";
import confetti from "canvas-confetti";
const canvasRef = ref<HTMLDivElement | null>(null);
const showPrizeCard = ref(false);
const showCanvas = ref(true);
const running = ref(false);
const rounds = ref<IRound[]>([]);
const currentRoundID = ref<string | undefined>();
const members =ref<Member[]>([])
const currentRound = computed(() => {
  return rounds.value?.find((round) => round.id === currentRoundID.value);
});

const refreshPrize = () => {
  return axios.get("/prize").then((res: any) => {
    rounds.value = res.data?.rounds || [];
    currentRoundID.value = res.data?.currentRoundID;
  });
 
};

const init = () => {
  return axios.get("/prize/member").then((res: any) => {
    //  console.log(res.data)
     members.value=res.data || []
       const canvas = canvasRef.value;
      if (!canvas) return;
      const minSize = Math.min(
        document.body.offsetWidth,
        document.body.offsetHeight
      );
      canvas.style.width = `${minSize * 0.9}px`;
      canvas.style.height = `${minSize * 0.9}px`;
     // 确保在 Vue 更新 DOM 后初始化 tagCanvas
     nextTick(() => {
      tagCanvas.Start("myCanvas", "tags", {
        dragControl: true,
        decel: 1,
        textFont: 'Impact,"Arial Black",sans-serif',
        textColour: "#fff",
        textHeight: 25,
        minSpeed: 0.01,
        initial: [0.1 * Math.random() + 0.01, -(0.1 * Math.random() + 0.01)],
      });
      tagCanvas.SetSpeed("myCanvas", speed);
      // 显示 tags div
      // showTags.value = true;
    });
  });
     
 
};

const getPrize = () => {
  refreshPrize().finally(() => {
    // setTimeout(() => {
    //   getPrize();
    // }, 1000);
  });
};

// 随机一个速度
const speed = [0.3, -0.15];
const turnAudio = new Audio(TurnMusic);
const resultAudio = new Audio(ResultMusic);
// 设置结果音乐只播放一次
resultAudio.loop = false;

const triggerConfetti = () => {
  // 增加持续时间和发射频率
  const duration = 4000; // 持续4秒
  const animationEnd = Date.now() + duration; // 添加这行定义
  const defaults = {
    startVelocity: 45, // 增加初始速度
    spread: 360,
    ticks: 100, // 增加粒子存活时间
    zIndex: 0,
  };

  const randomInRange = (min: number, max: number) => {
    return Math.random() * (max - min) + min;
  };

  // 立即发射一波大型烟花
  confetti({
    ...defaults,
    particleCount: 150,
    origin: { x: 0.5, y: 0.7 },
    gravity: 0.6, // 降低重力效果使粒子飞得更高
    scalar: 1, // 增大粒子尺寸
  });

  const interval: any = setInterval(function () {
    const timeLeft = animationEnd - Date.now();

    if (timeLeft <= 0) {
      return clearInterval(interval);
    }

    const particleCount = 80 * (timeLeft / duration); // 增加基础粒子数量

    // 从左右两侧发射
    confetti({
      ...defaults,
      particleCount,
      origin: { x: randomInRange(0.1, 0.3), y: Math.random() - 0.2 },
      gravity: 1.2, // 调整重力效果
      scalar: 1, // 增大粒子尺寸
    });
    confetti({
      ...defaults,
      particleCount,
      origin: { x: randomInRange(0.7, 0.9), y: Math.random() - 0.2 },
      gravity: 1.2,
      scalar: 1,
    });
  }, 200); // 缩短发射间隔，使效果更密集
};

onMounted(() => {
   init()


  getPrize();
 
});

const onStop = () => {
  if (!running.value) return;

  // 执行动画，组件隐藏云图
  showCanvas.value = false;
  let currentSpeed = 5;
  const setSpeed = async () => {
    if (currentSpeed <= speed[0]) {
      await axios.get(
        `/prize/winners?roundID=${currentRound.value?.id}&prize=${currentRound.value?.prize}&count=${currentRound.value?.count}`
      );

      await refreshPrize();

      // 动画彻底停止之后弹出卡片，重新激活云图
      showCanvas.value = true;

      // 在这里停止转动音乐并立即播放结果音乐
      turnAudio.pause();
      turnAudio.currentTime = 0;
      resultAudio.play();

      // 触发烟花效果
      setTimeout(() => {
        triggerConfetti();
      }, 500);

      setTimeout(() => {
        running.value = false;
      });

      nextTick(() => {
        // 只显示中奖者，不再在这里播放音乐
        showPrizeCard.value = true;
      });

      return;
    }

    currentSpeed -= 0.2;
    setTimeout(() => {
      tagCanvas.SetSpeed("myCanvas", [currentSpeed, speed[1]]);
      setSpeed();
    }, 50);
  };
  setSpeed();
};

const onStart = () => {
  if (running.value) return;
  if (!currentRound.value || currentRound.value?.state)
    return message.warn("请等待");
  let currentSpeed = 1;
  running.value = true;

  // 停止结果音乐（如果正在播放）
  resultAudio.pause();
  resultAudio.currentTime = 0;

  // 开始播放转动音乐
  turnAudio.loop = true;
  turnAudio.play();

  // 隐藏之前的图片
  showPrizeCard.value = false;
  const setSpeed = () => {
    if (currentSpeed >= 5) {
      // 速度跑到最满之后停止
      return;
    }
    currentSpeed += 0.2;
    setTimeout(() => {
      tagCanvas.SetSpeed("myCanvas", [currentSpeed, 0]);
      setSpeed();
    }, 50);
  };
  setSpeed();
};

useKeyMap("enter", (e) => {
  if (!currentRound.value || currentRound.value?.state) return;
  if (!running.value) {
    onStart();
  } else {
    onStop();
  }
  e.preventDefault();
});

// 组件卸载时确保音频停止
onUnmounted(() => {
  // 停止所有音频
  turnAudio.pause();
  turnAudio.currentTime = 0;
  resultAudio.pause();
  resultAudio.currentTime = 0;
});
</script>

<template>
  <main>
      <div class="sponsor"  v-if="showPrizeCard">
       <p>赞助商</p>
       <p>
          <ul>
            <li v-for="(sponsor, index) in currentRound?.zxs" :key="index">
              <img :src="sponsor.icon" alt="企业图标" class="option-icon" />
              <span>{{ sponsor.value }}</span>
            </li>
          </ul>
      </p>
      </div>

   
    <canvas
      ref="canvasRef"
      width="1000"
      height="1000"
      id="myCanvas"
      style="margin-top: -40px"
      :class="[showCanvas ? 'showCanvas' : 'hiddenCanvas']">
      <p>换个现代浏览器吧！</p>
    </canvas>
    <PrizeCard
      :winners="currentRound?.winners || []"
      :zzs="currentRound?.zxs||''"
      v-if="showPrizeCard" />
    
    <div
      id="tags"
      v-show="false">
     
      <ul>
        <li
          v-for="(tag, index) in members"
          :key="index">
          <a href="javascript:;">{{tag.name }}</a>
        </li>
      </ul>
    </div>
    <div class="buttons">
      <Button
        v-if="!running"
        @click="onStart"
        :disabled="currentRound?.state"
        class="start"
        >开始<svg
          width="14"
          height="16"
          viewBox="0 0 14 16"
          fill="none"
          xmlns="http://www.w3.org/2000/svg">
          <path
            d="M13.5 7.1263C14.1667 7.51461 14.1667 8.48539 13.5 8.8737L1.5 15.8633C0.833334 16.2516 -3.3649e-08 15.7663 0 14.9896L6.05683e-07 1.01037C6.39332e-07 0.233746 0.833334 -0.251645 1.5 0.136667L13.5 7.1263Z"
            fill="currentColor" />
        </svg>
      </Button>
      <Button
        v-else
        danger
        class="stop"
        @click="onStop"
        :disabled="!showCanvas || currentRound?.state"
        >抽取<svg
          width="15"
          height="15"
          viewBox="0 0 15 15"
          fill="none"
          xmlns="http://www.w3.org/2000/svg">
          <path
            d="M12.7109 15H2.28906C1.02539 15 0 13.9746 0 12.7109V2.28906C0 1.02539 1.02539 0 2.28906 0H12.709C13.9746 0 15 1.02539 15 2.28906V12.709C15 13.9746 13.9746 15 12.7109 15Z"
            fill="currentColor" />
        </svg>
      </Button>

      <div v-if="currentRound">
        <span
          class="text"
          v-if="!currentRound.state"
          >当前抽取的是{{ displayPrize(currentRound?.prize) }}
          {{ currentRound?.count }}个</span
        >
            

        <span
          class="text"
          v-else
          >抽取完毕</span
        >
      </div>
    </div>
  </main>
</template>

<style scoped lang="less">
main {
  width: 100vw;
  height: 100vh;
  background-image: url("./assets/bg.png");
  background-size: 100% 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  canvas {
    transform: scale(1);
    transition: all 1.2s ease-in;
    &.hiddenCanvas {
      transform: scale(0);
    }
  }
}
.sponsor {
  position: absolute; /* 绝对定位 */
  top: 350px; /* 距离顶部的距离 */
  right: 250px; /* 距离右侧的距离 */
  font-size: 16px;
  font-weight: bold;
  color: #333;
}
.ant-btn {
  height: 51px;
  border-radius: 8px;
  padding-left: 27px;
  padding-right: 27px;
  font-size: 20px;
  font-weight: 600;
}

.buttons {
  display: flex;
  align-items: center;
  position: fixed;
  left: 20px;
  bottom: 20px;
  color: #fff;

  .text {
    font-size: 16px;
  }

  .ant-btn.start {
    background-color: #ff5a1f;
    border: 1px solid #ffcd55;
    color: #fff;
    box-shadow: 0px 10px 6px 0px rgba(255, 90, 30, 0.3);
    position: relative;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    svg {
      margin-left: 20px;
    }
  }
  .ant-btn.stop {
    background-color: #fff;
    border: 1px solid rgba(255, 90, 31, 1);
    display: flex;
    align-items: center;
    justify-content: center;
    svg {
      margin-left: 24px;
    }
  }

  .ant-btn {
    &[disabled]:after {
      content: "";
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(255, 255, 255, 0.3);
    }
  }

  .text,
  :deep(.ant-btn),
  :deep(.ant-select) {
    margin-right: 10px;
  }
  :deep(.ant-select) {
    width: 140px;
    margin-right: 10px;
  }
  :deep(
      .ant-select-focused:not(.ant-select-customize-input) .ant-select-selector
    ) {
    border-color: red !important;
  }
  // :deep(
  //     .ant-select:hover:not(.ant-select-customize-input) .ant-select-selector
  //   ) {
  //   border-color: red !important;
  // }
  :deep(.ant-btn:not([disabled]):hover) {
    transform: scale(1.05);
    transform-origin: center center;
  }
}
.option-icon {
  width: 20px;
  height: 20px;
  margin-right: 8px;
}
</style>
